package org.zuel.lkq.component;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.zuel.lkq.domain.Perm;
import org.zuel.lkq.domain.Role;
import org.zuel.lkq.domain.User;
import org.zuel.lkq.service.AuthQueryService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: user用户授权基类
 * @Author: Athrun
 * @Date: 2019/4/7
 * @Version 1.0
 */
public abstract class UserAuthRealm extends AuthorizingRealm {

    @Autowired
    private AuthQueryService authQueryService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        Object principal = getAvailablePrincipal(principals);
        if(!(principal instanceof User)) {
            return null;
        }
        User curUser = (User) principal;

        List<Role> roleList = authQueryService.queryRolesByUser(curUser.getId());
        Set<String> roles = new HashSet<>();
        roleList.forEach(role -> {
            if(!roles.contains(role.getName())) {
                roles.add(role.getName());
            }});

        List<Perm> permList = authQueryService.queryPermsByUser(curUser.getId());
        Set<String> perms = new HashSet<>();
        permList.forEach(perm -> {
            if (!StringUtils.isEmpty(perm.getPermEl()) && !perms.contains(perm.getPermEl())) {
                perms.add(perm.getPermEl());
            }
        });

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(perms);
        return info;
    }
}
